﻿using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.EntityFrameworkCore;

namespace Fee.Stores.Ef
{
    public class FrameworkContractStore<T> : IFrameworkContractStore<T> where T : FeeDbContext
    {
        private readonly T _context;

        public FrameworkContractStore(T context)
        {
            _context = context;
        }

        public FrameworkContract GetById(int id, bool fullJoin)
        {
            var query = _context.FrameworkContracts;

            if (fullJoin)
                query = query.Include(f => f.Vendor);

            return query.FirstOrDefault(f => f.Id == id);
        }

        public IEnumerable<FrameworkContract> FindContractsByVendor(int vendorId,
            DateTimeOffset delegateOrderCreateTime)
        {
            var query = from contract in _context.FrameworkContracts.Include(f => f.Vendor)
                        where contract.Vendor.Id == vendorId
                              && (
                                  contract.ExpireTime == null ||
                                  delegateOrderCreateTime <= contract.ExpireTime
                              ) && delegateOrderCreateTime >= contract.SignTime
                        orderby contract.SignTime descending
                        select contract;
            return query;
        }
    }
}